package com.example.controller;

import com.example.dao.EmployeeDAO;
import com.example.model.Employee;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet("/employeeInfo")
public class EmployeeInfoServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 检查用户是否登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        String role = (String) session.getAttribute("role");
        int empId;

        try {
            // 管理员可以查看任何员工信息，员工只能查看自己的信息
            if ("admin".equals(role)) {
                empId = Integer.parseInt(request.getParameter("id"));
            } else {
                // 员工只能查看自己的信息
                empId = (int) ((com.example.model.User) session.getAttribute("user")).getEmpId();
            }

            EmployeeDAO employeeDAO = new EmployeeDAO();
            Employee employee = employeeDAO.getEmployeeById(empId);

            if (employee != null) {
                request.setAttribute("employee", employee);
                request.setAttribute("isAdmin", "admin".equals(role));
                RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/employeeInfo.jsp");
                dispatcher.forward(request, response);
            } else {
                response.sendRedirect("employees");
            }
        } catch (Exception e) {
            throw new ServletException("Error showing employee info", e);
        }
    }
}